package com.users.rn.kit.bridge.impl

import com.facebook.react.bridge.*
import com.facebook.react.modules.core.DeviceEventManagerModule
import com.users.rn.rncommon.util.RNPageTag

/**

 * 作者：wolf on 12/22/20 15:50

 * 邮箱：bluce

 */

class KitLifeCycleBridge constructor(context: ReactApplicationContext) : ReactContextBaseJavaModule(context), LifecycleEventListener {
    companion object {
        const val ON_RESUME: String = "onResume"
        const val ON_PAUSE: String = "onPause"
        const val ON_DESTROY: String = "onDestroy"
    }


    override fun getName(): String {
        return KitLifeCycleBridge::class.java.simpleName
    }

    override fun initialize() {
        super.initialize()
        reactApplicationContext?.addLifecycleEventListener(this)
    }

    override fun getConstants(): MutableMap<String, Any> {
        val map: MutableMap<String, Any> = mutableMapOf()
        map["onResume"] = ON_RESUME
        map["onPause"] = ON_PAUSE
        map["onDestroy"] = ON_DESTROY
        return map
    }

    override fun onHostDestroy() {
        reactApplicationContext?.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter::class.java)?.emit(ON_RESUME, getPageTag())
    }

    override fun onHostPause() {
        reactApplicationContext?.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter::class.java)?.emit(ON_PAUSE, getPageTag())
    }

    override fun onHostResume() {
        reactApplicationContext?.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter::class.java)?.emit(ON_DESTROY, getPageTag())
    }

    override fun onCatalystInstanceDestroy() {
        super.onCatalystInstanceDestroy()
        reactApplicationContext?.removeLifecycleEventListener(this)
    }

    private fun getPageTag(): WritableMap? {
        val map = Arguments.createMap()
        if (currentActivity != null && currentActivity is RNPageTag) {
            map.putString(RNPageTag.RN_KEY_PAGE_TAG, (currentActivity as RNPageTag).pageTag)
        }
        return map
    }
}